// 获取当前玩家信息
const currentPlayer = JSON.parse(localStorage.getItem('player'));

// 页面加载完成后初始化
$(document).ready(function() {
    if (!currentPlayer) {
        window.location.href = '/login';
        return;
    }

    // 加载玩家积分
    loadPlayerScore();
    
    // 加载商品列表
    loadShopItems();
    
    // 加载已购物品
    loadInventory();
    
    // 绑定标签页切换事件
    $('#shopTabs a').on('shown.bs.tab', function(e) {
        if (e.target.href.endsWith('inventory')) {
            loadInventory();
        }
    });
});

// 加载玩家积分
function loadPlayerScore() {
    $.get(`/api/players/${currentPlayer.id}`)
        .done(function(player) {
            $('#playerScore').text(player.score);
        })
        .fail(function(error) {
            showMessage('加载积分失败', 'error');
        });
}

// 加载商品列表
function loadShopItems() {
    $.get('/api/shop/items', { playerId: currentPlayer.id })
        .done(function(items) {
            const itemList = $('#itemList');
            itemList.empty();
            
            if (items.length === 0) {
                itemList.append('<div class="col-12 text-center">暂无可购买商品</div>');
                return;
            }
            
            items.forEach(item => {
                itemList.append(createItemCard(item));
            });
        })
        .fail(function(error) {
            showMessage('加载商品失败', 'error');
        });
}

// 加载已购物品
function loadInventory() {
    $.get(`/api/shop/player/${currentPlayer.id}/items`)
        .done(function(items) {
            const inventoryList = $('#inventoryList');
            inventoryList.empty();
            
            if (items.length === 0) {
                inventoryList.append('<div class="col-12 text-center">暂无物品</div>');
                return;
            }
            
            items.forEach(item => {
                inventoryList.append(createInventoryCard(item));
            });
        })
        .fail(function(error) {
            showMessage('加载物品失败', 'error');
        });
}

// 创建商品卡片
function createItemCard(item) {
    return `
        <div class="col-md-4 mb-4">
            <div class="item-card">
                <img src="${item.imageUrl}" class="item-image" alt="${item.name}">
                <div class="item-info">
                    <h5 class="item-name">${item.name}</h5>
                    <p class="item-description">${item.description}</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="item-price">
                            <i class="fas fa-coins me-1"></i>${item.price}
                        </div>
                        <button class="btn btn-purchase" onclick="purchaseItem(${item.id})">
                            购买
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 创建已购物品卡片
function createInventoryCard(item) {
    return `
        <div class="col-md-4 mb-4">
            <div class="item-card">
                <img src="${item.item.imageUrl}" class="item-image" alt="${item.item.name}">
                <div class="item-info">
                    <h5 class="item-name">${item.item.name}</h5>
                    <p class="item-description">${item.item.description}</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="purchase-time">
                            购买时间：${formatDate(item.purchaseTime)}
                        </div>
                        <button class="btn btn-purchase ${item.equipped ? 'active' : ''}" 
                                onclick="toggleEquip(${item.id})">
                            ${item.equipped ? '取消装备' : '装备'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 购买物品
function purchaseItem(itemId) {
    // 禁用按钮，防止重复点击
    const $btn = $(`button[onclick="purchaseItem(${itemId})"]`);
    $btn.prop('disabled', true);
    
    $.ajax({
        url: '/api/shop/purchase/' + itemId,
        method: 'POST',
        data: { playerId: currentPlayer.id }
    })
    .done(function(response) {
        showMessage('购买成功！', 'success');
        playPurchaseSound();
        loadPlayerScore();
        loadInventory();
        loadShopItems();
    })
    .fail(function(error) {
        let errorMessage = '购买失败';
        if (error.responseJSON && error.responseJSON.message) {
            errorMessage = error.responseJSON.message;
            
            // 根据错误类型显示不同样式
            if (errorMessage.includes('积分不足')) {
                showMessage(errorMessage, 'error');
            } else if (errorMessage.includes('已拥有')) {
                showMessage(errorMessage, 'warning');
            } else {
                showMessage(errorMessage, 'error');
            }
        } else {
            showMessage(errorMessage, 'error');
        }
    })
    .always(function() {
        // 延迟一下再启用按钮
        setTimeout(() => $btn.prop('disabled', false), 1000);
    });
}

// 装备/卸下物品
function toggleEquip(itemId) {
    $.ajax({
        url: '/api/shop/toggle-equip/' + itemId,
        method: 'POST',
        data: { playerId: currentPlayer.id }
    })
    .done(function(response) {
        showMessage('操作成功！', 'success');
        loadInventory();
    })
    .fail(function(error) {
        showMessage(error.responseJSON?.message || '操作失败', 'error');
    });
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 显示消息提示
function showMessage(message, type = 'info') {
    // 根据消息类型设置样式
    const styles = {
        error: {
            icon: '<i class="fas fa-times-circle"></i>',
            bgClass: 'bg-danger',
            title: '错误'
        },
        success: {
            icon: '<i class="fas fa-check-circle"></i>',
            bgClass: 'bg-success',
            title: '成功'
        },
        warning: {
            icon: '<i class="fas fa-exclamation-circle"></i>',
            bgClass: 'bg-warning text-dark',
            title: '警告'
        },
        info: {
            icon: '<i class="fas fa-info-circle"></i>',
            bgClass: 'bg-info',
            title: '提示'
        }
    };

    const style = styles[type] || styles.info;

    // 创建消息元素
    const messageElement = $(`
        <div class="message-popup">
            <div class="message-content ${style.bgClass}">
                <div class="message-icon">
                    ${style.icon}
                </div>
                <div class="message-text">
                    <div class="message-title">${style.title}</div>
                    <div class="message-body">${message}</div>
                </div>
            </div>
        </div>
    `);

    // 添加样式
    const styleElement = $(`
        <style>
            .message-popup {
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                z-index: 9999;
                animation: slideDown 0.3s ease-out;
            }

            .message-content {
                display: flex;
                align-items: center;
                padding: 15px 25px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                color: white;
                min-width: 300px;
            }

            .message-icon {
                font-size: 24px;
                margin-right: 15px;
            }

            .message-text {
                flex: 1;
            }

            .message-title {
                font-weight: 600;
                margin-bottom: 2px;
            }

            .message-body {
                font-size: 0.95em;
            }

            @keyframes slideDown {
                from {
                    transform: translate(-50%, -100%);
                    opacity: 0;
                }
                to {
                    transform: translate(-50%, 0);
                    opacity: 1;
                }
            }

            @keyframes fadeOut {
                from {
                    opacity: 1;
                }
                to {
                    opacity: 0;
                }
            }
        </style>
    `);

    // 添加到页面
    $('head').append(styleElement);
    $('body').append(messageElement);

    // 3秒后消失
    setTimeout(() => {
        messageElement.css('animation', 'fadeOut 0.3s ease-out forwards');
        setTimeout(() => {
            messageElement.remove();
            styleElement.remove();
        }, 300);
    }, 3000);
}

// 播放购买成功音效
function playPurchaseSound() {
    const audio = new Audio('/audio/purchase.mp3');
    audio.volume = 0.5;
    audio.play().catch(e => console.log('无法播放音效:', e));
}

// 添加 CSS 动画
const style = `
<style>
    @keyframes slideIn {
        from { transform: translateX(100%); }
        to { transform: translateX(0); }
    }
    
    @keyframes slideOut {
        from { transform: translateX(0); }
        to { transform: translateX(100%); }
    }
    
    .toast {
        min-width: 250px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        border-radius: 8px;
        overflow: hidden;
    }
    
    .toast .toast-header {
        padding: 0.75rem 1rem;
    }
    
    .toast .toast-body {
        padding: 1rem;
        font-size: 0.95rem;
    }
    
    .toast .btn-close {
        filter: brightness(0) invert(1);
    }
    
    .bg-warning .btn-close {
        filter: none;
    }
</style>
`;

// 添加样式到页面
$('head').append(style); 